package com.cn.wanxi.util;

import com.alibaba.fastjson.JSONObject;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//@WebFilter("/*")
public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /**
     * 过滤器的放行操作
     *
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
//        不能每一个访问后台的接口都判断是否已经登录，至少登录和注册还有验证码不能判断
//        拿到访问后台的接口地址
        String path = req.getServletPath();
        System.out.println(path);
//        只有访问后台的地址，才判断是否已经登录
//        做图片上传时，也不能进如过滤器，不能判断是否登录，直接在当前接口判断是否已经登录
        if (path.startsWith("/back/")) {
            boolean isLogin = req.getSession().getAttribute("username") != null;
            if (isLogin) {
                filterChain.doFilter(req, resp);
            } else {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("result", -1);
                servletResponse.getWriter().println(jsonObject);
//                resp.sendRedirect("/html/login.html");
            }
        } else {
//            放行
            filterChain.doFilter(req, resp);
        }

    }

    @Override
    public void destroy() {

    }
}
